<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel 文件处理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container { padding-top: 2rem; }
        #result { margin-top: 2rem; }
        .debug-info { 
            margin-top: 1rem;
            padding: 1rem;
            background-color: #f8f9fa;
            border-radius: 0.25rem;
            font-family: monospace;
        }
        .loading {
            display: none;
            margin: 1rem 0;
        }
        .loading.active {
            display: block;
        }
        #downloadSection {
            margin: 1rem 0;
            display: none;
        }
        .sheet-section {
            margin-bottom: 2rem;
            border: 1px solid #dee2e6;
            border-radius: 0.25rem;
            padding: 1rem;
        }
        .sheet-title {
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #dee2e6;
        }
        .sheet-info {
            margin-bottom: 1rem;
            font-size: 0.9rem;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="mb-4">Excel 文件处理</h1>
        
        <div class="card">
            <div class="card-body">
                <form id="uploadForm">
                    <div class="mb-3">
                        <label for="excelFile" class="form-label">选择Excel文件</label>
                        <input type="file" class="form-control" id="excelFile" accept=".xlsx,.xls" required>
                    </div>
                    <button type="submit" class="btn btn-primary">上传并处理</button>
                </form>
            </div>
        </div>

        <div class="loading">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <span class="ms-2">正在处理文件...</span>
        </div>

        <div id="downloadSection" class="alert alert-success">
            <h5>处理完成！</h5>
            <p>数据已转换为JSON格式，您可以：</p>
            <a id="downloadLink" href="#" class="btn btn-success" download>
                <i class="bi bi-download"></i> 下载JSON文件
            </a>
            <div class="mt-2">
                <small class="text-muted">提示：JSON文件包含所有工作表的数据</small>
            </div>
        </div>

        <div id="alert" class="alert mt-3" style="display: none;"></div>

        <div class="debug-info" id="debugInfo" style="display: none;">
            <h5>调试信息</h5>
            <pre><code id="debugContent"></code></pre>
        </div>

        <div id="result"></div>
    </div>

    <script>
        const form = document.getElementById('uploadForm');
        const loading = document.querySelector('.loading');
        const alert = document.getElementById('alert');
        const debugInfo = document.getElementById('debugInfo');
        const debugContent = document.getElementById('debugContent');
        const downloadSection = document.getElementById('downloadSection');
        const downloadLink = document.getElementById('downloadLink');
        const result = document.getElementById('result');

        function showAlert(message, type = 'danger') {
            alert.className = `alert alert-${type} mt-3`;
            alert.textContent = message;
            alert.style.display = 'block';
        }

        function showDebugInfo(debug) {
            debugContent.textContent = JSON.stringify(debug, null, 2);
            debugInfo.style.display = 'block';
        }

        function hideDebugInfo() {
            debugInfo.style.display = 'none';
        }

        function showDownloadSection(downloadUrl) {
            downloadLink.href = downloadUrl;
            downloadSection.style.display = 'block';
        }

        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const fileInput = document.getElementById('excelFile');
            const file = fileInput.files[0];
            
            if (!file) {
                showAlert('请选择一个文件');
                return;
            }

            // 清除之前的显示
            alert.style.display = 'none';
            hideDebugInfo();
            downloadSection.style.display = 'none';
            result.innerHTML = '';

            // 显示加载状态
            loading.classList.add('active');

            try {
                const formData = new FormData();
                formData.append('file', file);

                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    if (result.debug) {
                        showDebugInfo(result.debug);
                    }
                    
                    if (result.data) {
                        displayAllSheets(result.data);
                        showAlert(`成功处理了 ${result.debug.processedSheets} 个工作表，共 ${result.debug.totalRows} 行数据`, 'success');
                        
                        if (result.downloadUrl) {
                            showDownloadSection(result.downloadUrl);
                        }
                    } else {
                        showAlert('文件中没有找到有效数据');
                    }
                } else {
                    showAlert(result.error);
                    if (result.debug) {
                        showDebugInfo(result.debug);
                    }
                }
            } catch (error) {
                showAlert(`处理失败: ${error.message}`);
                console.error(error);
            } finally {
                loading.classList.remove('active');
                fileInput.value = ''; // 清除文件选择
            }
        });

        function displayAllSheets(sheets) {
            result.innerHTML = ''; // 清空现有内容

            for (const [sheetName, sheetInfo] of Object.entries(sheets)) {
                if (sheetInfo.error) {
                    // 如果工作表有错误，显示错误信息
                    const errorDiv = document.createElement('div');
                    errorDiv.className = 'sheet-section';
                    errorDiv.innerHTML = `
                        <h3 class="sheet-title">${sheetName}</h3>
                        <div class="alert alert-danger">
                            解析错误: ${sheetInfo.error}
                        </div>
                    `;
                    result.appendChild(errorDiv);
                    continue;
                }

                const sheetDiv = document.createElement('div');
                sheetDiv.className = 'sheet-section';
                
                // 添加工作表标题和信息
                sheetDiv.innerHTML = `
                    <h3 class="sheet-title">${sheetName}</h3>
                    <div class="sheet-info">
                        <strong>行数:</strong> ${sheetInfo.rowCount} | 
                        <strong>范围:</strong> ${sheetInfo.range}
                    </div>
                `;

                // 创建表格
                const table = document.createElement('table');
                table.className = 'table table-striped';
                
                // 添加表头
                const thead = document.createElement('thead');
                const headerRow = document.createElement('tr');
                sheetInfo.headers.forEach(header => {
                    const th = document.createElement('th');
                    th.textContent = header;
                    headerRow.appendChild(th);
                });
                thead.appendChild(headerRow);
                table.appendChild(thead);

                // 添加数据行
                const tbody = document.createElement('tbody');
                sheetInfo.data.forEach(row => {
                    const tr = document.createElement('tr');
                    sheetInfo.headers.forEach(header => {
                        const td = document.createElement('td');
                        td.textContent = row[header] !== undefined && row[header] !== null 
                            ? row[header] 
                            : '';
                        tr.appendChild(td);
                    });
                    tbody.appendChild(tr);
                });
                table.appendChild(tbody);

                // 将表格添加到工作表区域
                sheetDiv.appendChild(table);
                result.appendChild(sheetDiv);
            }
        }
    </script>
</body>
</html> 